import { _decorator, Button, Component, director, find, input, Input, instantiate, Layers, log, Node, Prefab, resources, Sprite, SpriteFrame, TextAsset } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('NewComponent')
export class NewComponent extends Component {

    @property
    Player_Speed: number = 0.1;
    @property(Prefab)
    OtherCar: Prefab = null;
    CarNode: Node = null;

    parseCSV(text: string): string[][] {
        const rows = text.trim().split('\n');
        return rows.map(row => row.split(','));
    }
    onLoad() {
        console.log('GBR ====OnLoad');
        input.on(Input.EventType.KEY_DOWN, this.Key_Down, this);

        this.CarNode = instantiate(this.OtherCar);
        this.CarNode.setParent(this.node)
        this.CarNode.setPosition(this.node.x + 1, this.node.y, this.node.y)

    }
    start() {
        let Btn = this.node.getChildByName("Button")
        if (Btn) {
            Btn.on(Button.EventType.CLICK, this.OnBindButtonClick);
        }
        this.loadCSV();
        console.log('gbr')


    }
    idPathMap = new Map<Number, string>();
    private loadCSV() {
        resources.load("Config/Table", TextAsset, (err: Error | null, textAsset: TextAsset) => {
            if (err) {
                console.error("CSV 加载失败", err);
                return;
            }

            const csvText = textAsset.text;
            const rows = csvText.trim().split('\n'); // 按行分割
            const headers = rows[0].split(','); // 标题行

            // 2. 遍历数据行，填充 Map
            for (let i = 1; i < rows.length; i++) {
                const row = rows[i].split(',');
                const id = parseInt(row[0]); // 第一列为 ID
                const path = row[1]?.trim(); // 第二列为 Path

                // 避免无效数据
                if (!isNaN(id) && path) {
                    this.idPathMap.set(id, path);
                }
            }

            console.log("Map 初始化完成", this.idPathMap);

        });
    }

    public async loadImageSync(name: string): Promise<SpriteFrame | null> {
        if (name == '' || name == undefined) {
            return null;
        }

        return new Promise((resolve, reject) => {
            console.log(name + 'gbr')
            resources.load(name + "/spriteFrame", SpriteFrame, (err, spriteFrame) => {

                if (err) {
                    console.error("加载失败详情：", err.message); // 输出具体错误类型
                    return;
                }
                if (spriteFrame) {
                    resolve(spriteFrame);
                }
                else {
                    console.error('[cocos_hmi] loadImageSync fail :' + name);
                    console.error("[cocos_hmi] loadImageSync error:" + err);
                    reject(err);
                }
            });
        });
    }

    private createSpriteNode(name: string, frame: SpriteFrame) {
        let node = find("Canvas/" + name); // 检查是否已存在同名节点
        if (!node) {
            node = new Node();
            node.name = name;
            const sprite = node.addComponent(Sprite);
            sprite.spriteFrame = frame;
            node.layer = Layers.Enum.UI_2D;
            node.parent = find("Canvas")!;
        } else {
            // 若已存在，可更新资源或提示
            node.getComponent(Sprite)!.spriteFrame = frame;
        }
    }

    async OnBindButtonClick(event: Event, customEventData: string) {

        const value = this.idPathMap.get(+customEventData);
        console.log(value + 'gbr');

        try {
            const frame = await this.loadImageSync('Image/' + value); // 等待Promise解析
            if (frame) {
                // 创建节点并设置SpriteFrame
                this.createSpriteNode(value, frame);
            } else {
                console.warn("图片名无效或加载为空");
            }
        } catch (err) {
            console.error("资源加载失败：", err);
        }
    }



    update(deltaTime: number) {


        let CurSpeed = this.Player_Speed * deltaTime;
        let Pos = this.node.getPosition()
        this.node.setPosition(Pos.x, Pos.y, Pos.z + CurSpeed)
    }

    lateUpdate(deltaTime: number) {
        //console.log('GBR ====lateUpdate');
    }


    onDestroy() {
        console.log('GBR=onDestroy');
    }
    onDisable() {
        console.log('GBR=onDisable');
    }

    onEnable() {
        console.log('GBR=onEnable');
    }
    onFocusInEditor() {
        console.log('GBR=onFocusInEditor');
    }
    onLostFocusInEditor() {
        console.log('GBR=onLostFocusInEditor');
    }
    onRestore() {
        console.log('GBR=onRestore');
    }


    Key_Down(Key) {
        //console.log(Key)
        if (Key.keyCode == 65) {
            console.log('按下A')
        } else if (Key.keyCode == 68) {
            console.log('按下D')
        }

    }
}


